<?php
require_once '../config/database.php';
require_once '../utils/Database.php';
require_once '../utils/Response.php';

$db = new Database();

// JSON响应函数
function sendJson($data) {
    header('Content-Type: application/json; charset=utf-8');
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
    header('Access-Control-Allow-Headers: Content-Type, Authorization');
    
    if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
        exit;
    }
    
    echo json_encode($data, JSON_UNESCAPED_UNICODE);
    exit;
}

// 数据库连接
try {
    $pdo = new PDO(
        'mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=' . DB_CHARSET,
        DB_USER,
        DB_PASS,
        [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
        ]
    );
} catch (PDOException $e) {
    sendJson([
        'code' => 500,
        'message' => '数据库连接失败',
        'data' => null
    ]);
}

$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? '';
$input = json_decode(file_get_contents('php://input'), true);

switch ($method) {
    case 'GET':
        switch ($action) {
            case 'list':
                try {
                    $date = $_GET['date'] ?? '';
                    $status = $_GET['status'] ?? '';
                    $keyword = $_GET['keyword'] ?? '';
                    $type = $_GET['type'] ?? ''; // 'personal', 'team', 或空表示全部
                    
                    // 分页参数
                    $page = max(1, (int)($_GET['page'] ?? 1));
                    $limit = min(100, max(10, (int)($_GET['limit'] ?? 20)));
                    $offset = ($page - 1) * $limit;
                    
                    $whereClause = [];
                    $params = [];
                    
                    // 如果只查询个人预约
                    if ($type === 'personal') {
                        $whereClause[] = "r.reservation_type = 'personal' OR r.reservation_type IS NULL";
                    }
                    
                    // 日期筛选
                    if ($date) {
                        $whereClause[] = "r.visit_date = ?";
                        $params[] = $date;
                    }
                    
                    // 状态筛选
                    if ($status !== '') {
                        $whereClause[] = "r.status = ?";
                        $params[] = $status;
                    }
                    
                    // 类型筛选
                    if ($type && $type !== 'personal') {
                        $whereClause[] = "r.reservation_type = ?";
                        $params[] = $type;
                    }
                    
                    // 搜索关键词
                    if ($keyword) {
                        $whereClause[] = "(r.visitor_name LIKE ? OR r.visitor_phone LIKE ? OR r.reservation_code LIKE ? OR u.nickname LIKE ?)";
                        $keywordPattern = "%$keyword%";
                        $params = array_merge($params, [$keywordPattern, $keywordPattern, $keywordPattern, $keywordPattern]);
                    }
                    
                    $whereSQL = $whereClause ? 'WHERE ' . implode(' AND ', $whereClause) : '';
                    
                    // 获取总数
                    $countSql = "SELECT COUNT(*) as total FROM reservations r 
                                LEFT JOIN users u ON r.user_id = u.id 
                                $whereSQL";
                    $countStmt = $pdo->prepare($countSql);
                    $countStmt->execute($params);
                    $totalCount = $countStmt->fetch()['total'];
                    $totalPages = ceil($totalCount / $limit);
                    
                    // 获取个人预约数据
                    $sql = "SELECT 
                        r.id,
                        r.reservation_code,
                        r.reservation_type,
                        r.visitor_name,
                        r.visitor_phone,
                        r.visitor_count,
                        r.visit_date,
                        r.status,
                        r.check_in_time,
                        r.created_at,
                        r.notes,
                        r.visitor_id_card,
                        ts.slot_name,
                        ts.start_time,
                        ts.end_time,
                        u.nickname as user_nickname,
                        (SELECT COUNT(*) FROM reservation_companions WHERE reservation_id = r.id) as companion_count
                    FROM reservations r
                    LEFT JOIN museum_time_slots ts ON r.time_slot_id = ts.id
                    LEFT JOIN users u ON r.user_id = u.id
                    $whereSQL
                    ORDER BY r.created_at DESC
                    LIMIT $limit OFFSET $offset";
                    
                    $stmt = $pdo->prepare($sql);
                    $stmt->execute($params);
                    $reservations = $stmt->fetchAll();
                    
                    sendJson([
                        'code' => 200,
                        'message' => '获取成功',
                        'data' => [
                            'reservations' => $reservations,
                            'pagination' => [
                                'current_page' => $page,
                                'total_pages' => $totalPages,
                                'total_count' => $totalCount,
                                'per_page' => $limit
                            ]
                        ]
                    ]);
                } catch (Exception $e) {
                    sendJson([
                        'code' => 500,
                        'message' => '获取预约列表失败: ' . $e->getMessage(),
                        'data' => null
                    ]);
                }
                break;
                
            case 'search':
                try {
                    $name = $_GET['name'] ?? '';
                    $idCard = $_GET['id_card'] ?? '';
                    $phone = $_GET['phone'] ?? '';
                    $status = $_GET['status'] ?? '';
                    $startDate = $_GET['start_date'] ?? '';
                    $endDate = $_GET['end_date'] ?? '';
                    $type = $_GET['type'] ?? 'personal';
                    
                    // 分页参数
                    $page = max(1, (int)($_GET['page'] ?? 1));
                    $limit = min(100, max(10, (int)($_GET['limit'] ?? 20)));
                    $offset = ($page - 1) * $limit;
                    
                    $whereClause = [];
                    $params = [];
                    
                    // 限制为个人预约
                    if ($type === 'personal') {
                        $whereClause[] = "(r.reservation_type = 'personal' OR r.reservation_type IS NULL)";
                    }
                    
                    // 姓名搜索
                    if ($name) {
                        $whereClause[] = "r.visitor_name LIKE ?";
                        $params[] = "%$name%";
                    }
                    
                    // 证件号搜索
                    if ($idCard) {
                        $whereClause[] = "r.visitor_id_card LIKE ?";
                        $params[] = "%$idCard%";
                    }
                    
                    // 联系方式搜索
                    if ($phone) {
                        $whereClause[] = "r.visitor_phone LIKE ?";
                        $params[] = "%$phone%";
                    }
                    
                    // 状态筛选
                    if ($status) {
                        $whereClause[] = "r.status = ?";
                        $params[] = $status;
                    }
                    
                    // 日期范围
                    if ($startDate) {
                        $whereClause[] = "r.visit_date >= ?";
                        $params[] = $startDate;
                    }
                    
                    if ($endDate) {
                        $whereClause[] = "r.visit_date <= ?";
                        $params[] = $endDate;
                    }
                    
                    $whereSQL = $whereClause ? 'WHERE ' . implode(' AND ', $whereClause) : '';
                    
                    // 获取搜索结果总数
                    $countSql = "SELECT COUNT(*) as total FROM reservations r 
                                LEFT JOIN users u ON r.user_id = u.id 
                                $whereSQL";
                    $countStmt = $pdo->prepare($countSql);
                    $countStmt->execute($params);
                    $totalCount = $countStmt->fetch()['total'];
                    $totalPages = ceil($totalCount / $limit);
                    
                    $sql = "SELECT 
                        r.id,
                        r.reservation_code,
                        r.reservation_type,
                        r.visitor_name,
                        r.visitor_phone,
                        r.visitor_count,
                        r.visit_date,
                        r.status,
                        r.check_in_time,
                        r.created_at,
                        r.notes,
                        r.visitor_id_card,
                        ts.slot_name,
                        ts.start_time,
                        ts.end_time,
                        u.nickname as user_nickname
                    FROM reservations r
                    LEFT JOIN museum_time_slots ts ON r.time_slot_id = ts.id
                    LEFT JOIN users u ON r.user_id = u.id
                    $whereSQL
                    ORDER BY r.created_at DESC
                    LIMIT $limit OFFSET $offset";
                    
                    $stmt = $pdo->prepare($sql);
                    $stmt->execute($params);
                    $reservations = $stmt->fetchAll();
                    
                    sendJson([
                        'code' => 200,
                        'message' => '搜索成功',
                        'data' => [
                            'reservations' => $reservations,
                            'pagination' => [
                                'current_page' => $page,
                                'total_pages' => $totalPages,
                                'total_count' => $totalCount,
                                'per_page' => $limit
                            ]
                        ]
                    ]);
                } catch (Exception $e) {
                    sendJson([
                        'code' => 500,
                        'message' => '搜索失败: ' . $e->getMessage(),
                        'data' => null
                    ]);
                }
                break;
                
            case 'detail':
                try {
                    $id = $_GET['id'] ?? 0;
                    $type = $_GET['type'] ?? 'personal';
                    
                    if (!$id) {
                        sendJson([
                            'code' => 400,
                            'message' => '缺少预约ID',
                            'data' => null
                        ]);
                    }
                    
                    if ($type === 'team') {
                        $sql = "SELECT 
                            tr.*,
                            u.nickname as user_nickname,
                            u.real_name as user_real_name,
                            au.username as approved_by_name
                        FROM team_reservations tr
                        LEFT JOIN users u ON tr.user_id = u.id
                        LEFT JOIN admin_users au ON tr.approved_by = au.id
                        WHERE tr.id = ?";
                    } else {
                        $sql = "SELECT 
                            r.*,
                            ts.slot_name,
                            ts.start_time,
                            ts.end_time,
                            u.nickname as user_nickname,
                            u.real_name as user_real_name
                        FROM reservations r
                        LEFT JOIN museum_time_slots ts ON r.time_slot_id = ts.id
                        LEFT JOIN users u ON r.user_id = u.id
                        WHERE r.id = ?";
                    }
                    
                    $stmt = $pdo->prepare($sql);
                    $stmt->execute([$id]);
                    $reservation = $stmt->fetch();
                    
                    if (!$reservation) {
                        sendJson([
                            'code' => 404,
                            'message' => '预约不存在',
                            'data' => null
                        ]);
                    }
                    
                    // 如果是个人预约，获取同伴信息
                    if ($type === 'personal') {
                        $companionSql = "SELECT * FROM reservation_companions WHERE reservation_id = ?";
                        $companionStmt = $pdo->prepare($companionSql);
                        $companionStmt->execute([$id]);
                        $reservation['companions'] = $companionStmt->fetchAll();
                    }
                    
                    sendJson([
                        'code' => 200,
                        'message' => '获取成功',
                        'data' => $reservation
                    ]);
                } catch (Exception $e) {
                    sendJson([
                        'code' => 500,
                        'message' => '获取预约详情失败: ' . $e->getMessage(),
                        'data' => null
                    ]);
                }
                break;
                
            case 'statistics':
                try {
                    $date = $_GET['date'] ?? date('Y-m-d');
                    
                    // 个人预约统计
                    $personalStats = $pdo->prepare("
                        SELECT 
                            COUNT(*) as total_count,
                            SUM(CASE WHEN status = 'confirmed' THEN 1 ELSE 0 END) as confirmed_count,
                            SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) as pending_count,
                            SUM(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END) as cancelled_count,
                            SUM(CASE WHEN check_in_time IS NOT NULL THEN 1 ELSE 0 END) as checked_in_count,
                            SUM(visitor_count) as total_visitors
                        FROM reservations 
                        WHERE visit_date = ?
                    ");
                    $personalStats->execute([$date]);
                    $personal = $personalStats->fetch();
                    
                    // 团队预约统计
                    $teamStats = $pdo->prepare("
                        SELECT 
                            COUNT(*) as total_count,
                            SUM(CASE WHEN status = 'approved' THEN 1 ELSE 0 END) as approved_count,
                            SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) as pending_count,
                            SUM(CASE WHEN status = 'rejected' THEN 1 ELSE 0 END) as rejected_count,
                            SUM(visitor_count) as total_visitors
                        FROM team_reservations 
                        WHERE reservation_date = ?
                    ");
                    $teamStats->execute([$date]);
                    $team = $teamStats->fetch();
                    
                    sendJson([
                        'code' => 200,
                        'message' => '获取成功',
                        'data' => [
                            'date' => $date,
                            'personal' => $personal,
                            'team' => $team
                        ]
                    ]);
                } catch (Exception $e) {
                    sendJson([
                        'code' => 500,
                        'message' => '获取统计失败: ' . $e->getMessage(),
                        'data' => null
                    ]);
                }
                break;
                
            default:
                sendJson([
                    'code' => 400,
                    'message' => '无效的操作',
                    'data' => null
                ]);
        }
        break;
        
    case 'POST':
        switch ($action) {
            case 'update_status':
                try {
                    if (!isset($input['id']) || !isset($input['status']) || !isset($input['type'])) {
                        sendJson([
                            'code' => 400,
                            'message' => '缺少必要参数',
                            'data' => null
                        ]);
                    }
                    
                    $id = $input['id'];
                    $status = $input['status'];
                    $type = $input['type'];
                    $notes = $input['notes'] ?? '';
                    
                    if ($type === 'team') {
                        $sql = "UPDATE team_reservations SET status = ?, admin_notes = ?, updated_at = NOW() WHERE id = ?";
                        $stmt = $pdo->prepare($sql);
                        $result = $stmt->execute([$status, $notes, $id]);
                    } else {
                        $sql = "UPDATE reservations SET status = ?, notes = ?, updated_at = NOW() WHERE id = ?";
                        $stmt = $pdo->prepare($sql);
                        $result = $stmt->execute([$status, $notes, $id]);
                    }
                    
                    if ($result) {
                        sendJson([
                            'code' => 200,
                            'message' => '状态更新成功',
                            'data' => null
                        ]);
                    } else {
                        sendJson([
                            'code' => 500,
                            'message' => '状态更新失败',
                            'data' => null
                        ]);
                    }
                } catch (Exception $e) {
                    sendJson([
                        'code' => 500,
                        'message' => '状态更新失败: ' . $e->getMessage(),
                        'data' => null
                    ]);
                }
                break;
                
            default:
                sendJson([
                    'code' => 400,
                    'message' => '无效的操作',
                    'data' => null
                ]);
        }
        break;
        
    case 'DELETE':
        if ($action === 'delete') {
            try {
                $id = $_GET['id'] ?? 0;
                $type = $_GET['type'] ?? 'personal';
                
                if (!$id) {
                    sendJson([
                        'code' => 400,
                        'message' => '缺少预约ID',
                        'data' => null
                    ]);
                }
                
                if ($type === 'team') {
                    $stmt = $pdo->prepare("DELETE FROM team_reservations WHERE id = ?");
                } else {
                    // 先删除同伴记录
                    $companionStmt = $pdo->prepare("DELETE FROM reservation_companions WHERE reservation_id = ?");
                    $companionStmt->execute([$id]);
                    
                    $stmt = $pdo->prepare("DELETE FROM reservations WHERE id = ?");
                }
                
                $result = $stmt->execute([$id]);
                
                if ($result) {
                    sendJson([
                        'code' => 200,
                        'message' => '删除成功',
                        'data' => null
                    ]);
                } else {
                    sendJson([
                        'code' => 500,
                        'message' => '删除失败',
                        'data' => null
                    ]);
                }
            } catch (Exception $e) {
                sendJson([
                    'code' => 500,
                    'message' => '删除失败: ' . $e->getMessage(),
                    'data' => null
                ]);
            }
        } else {
            sendJson([
                'code' => 400,
                'message' => '无效的操作',
                'data' => null
            ]);
        }
        break;
        
    default:
        sendJson([
            'code' => 405,
            'message' => '不支持的请求方法',
            'data' => null
        ]);
}
?>